using System;
using System.Threading.Tasks;
using Automation.Data.Entity;
using Automation.Data.Helper;
using MySql.Data.MySqlClient;
using MySqlHelper = Automation.Data.Helper.MySqlHelper;

namespace Automation.Data.Service
{
    public class UserRepository : IUserRepository
    {
        private readonly MySqlHelper _mySqlHelper;

        public UserRepository(MySqlHelper mySqlHelper)
        {
            _mySqlHelper = mySqlHelper;
        }

        public async Task<User> GetUserByUsernameAsync(string username)
        {
            string sql = "SELECT * FROM user WHERE username = @username LIMIT 1";
            var param = new MySqlParameter("@username", username);
            var dt = await Task.Run(() => _mySqlHelper.ExecuteDataTable(sql, param));
            if (dt.Rows.Count == 0) return null;

            var row = dt.Rows[0];
            return new User
            {
                ID = Convert.ToInt32(row["ID"]),
                UserName = row["UserName"].ToString(),
                Password = row["Password"].ToString(),
                Tocken = row["Tocken"]?.ToString(),
                LastLoginDate = row["LastLoginDate"] == DBNull.Value ? null : (DateTime?)Convert.ToDateTime(row["LastLoginDate"]),
                ExpiryDate = row["ExpiryDate"] == DBNull.Value ? null : (DateTime?)Convert.ToDateTime(row["ExpiryDate"])
            };
        }

        public async Task<bool> UpdateUserAsync(User user)
        {
            string sql = @"UPDATE user SET 
                tocken = @tocken, 
                lastlogindate = @lastlogindate 
                WHERE id = @id";
            var paramTocken = new MySqlParameter("@tocken", user.Tocken ?? (object)DBNull.Value);
            var paramLastLogin = new MySqlParameter("@lastlogindate", user.LastLoginDate ?? (object)DBNull.Value);
            var paramId = new MySqlParameter("@id", user.ID);
            int result = await Task.Run(() => _mySqlHelper.ExecuteNonQuery(sql, paramTocken, paramLastLogin, paramId));
            return result > 0;
        }

    }
}